#include "XComponentBackend.h"
#include "GameStreamManager.h"
#include "video/VideoProcessor.h"
#include "core/utils/XComponentUtils.h"
#include "control/touch_screen/AbstractTouchScreenControlHandler.h"
#include <native_window/external_window.h>
#include <native_image/graphic_error_code.h>

#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN  0x0
#define LOG_TAG     "XComponentCallbacks"
#include <hilog/log.h>


void XComponentBackend::XComponentCallbacks::OnSurfaceCreated(OH_NativeXComponent *comp, void *win) {
    const auto id = XComponentUtils::getId(comp);
    if (!id) {
        return;
    }
    auto &self = getOrCreateInstance(*id);
    self.videoProcessor->nativeWindow = reinterpret_cast<OHNativeWindow*>(win);
    if (int nativeError = OH_NativeWindow_NativeWindowSetScalingModeV2(self.videoProcessor->nativeWindow, OH_SCALING_MODE_SCALE_TO_WINDOW_V2); nativeError != NATIVE_ERROR_OK) {
        OH_LOG_WARN(LOG_APP, "Failed to set native window scaling mode");
        return;
    }
}

void XComponentBackend::XComponentCallbacks::OnSurfaceChanged(OH_NativeXComponent *comp, void *win) {
}

void XComponentBackend::XComponentCallbacks::OnSurfaceDestroyed(OH_NativeXComponent *comp, void *win) {
    const auto id = XComponentUtils::getId(comp);
    if (!id) {
        return;
    }
    OH_LOG_DEBUG(LOG_APP, "OnSurfaceDestroyed triggered for XComponent id %{public}s", id->c_str());
    release(*id);
    GameStreamManager::cleanup();
}

void XComponentBackend::XComponentCallbacks::DispatchTouchEvent(OH_NativeXComponent *comp, void *win) {
    OH_NativeXComponent_TouchEvent touchEvent;
    if (auto res = OH_NativeXComponent_GetTouchEvent(comp, win, &touchEvent); res != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        OH_LOG_WARN(LOG_APP, "Failed to get touch event %{public}d", res);
        return;
    }
    INIT_XCOMPONENT_SELF_OR_ELSE(return);
    self.touchHandler->handle(comp, win, touchEvent);
}
